package com.zxl.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class downFile {

	public static void main(String args[]){
		boolean b = false;
		b = downFile("192.168.0.121",21,"anonymous","","/apache-tomcat-6.0.33/webapps/hnshzh","","E:\\download\\hnshzh");
		System.out.println("b:" + b);
	}
	
	/**
	 * Description: 从FTP服务器下载文件
	 * @param url FTP服务器hostname
	 * @param port FTP服务器端口
	 * @param username FTP登录账号
	 * @param password FTP登录密码
	 * @param remotePath FTP服务器上的相对路径
	 * @param fileName 要下载的文件名
	 * @param localPath 下载后保存到本地的路径
	 * @return
	 */
	public static boolean downFile(String url, int port, String username, String password, String remotePath,String fileName,String localPath) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);			//如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);//登录
			reply = ftp.getReplyCode();
			System.out.println("reply:" + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			traverse(ftp,remotePath,localPath);
			ftp.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	
	public static void traverse(FTPClient ftp, String remotePath, String localPath){
		try{
			ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for(FTPFile ff:fs){
				File localFile = new File(localPath+"/"+ff.getName());
				if(ff.isDirectory()){
					if(!localFile.exists()){
						localFile.mkdir();
					}
					if(!ff.getName().equals(".") && !ff.getName().equals("..")){
						String tempDir = ftp.printWorkingDirectory() + "/" + ff.getName();
//						System.out.println("文件夹：" + ff.getName() + "\t" + "tempDir:" + tempDir);
						traverse(ftp,tempDir,localPath + "/" + ff.getName());
						ftp.changeWorkingDirectory(remotePath);//很重要
					}
				}else{
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
//					System.out.println("文件：" + ff.getName());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
